#!/bin/python
# -*- coding: utf8 -*-

import oss2
import fittness
import func
import base64
import hmac
from hashlib import sha1 as sha
import urllib


class cli:
    def __init__(self):
        self.__auth = oss2.Auth(fittness.OSS[1], fittness.OSS[2])
        self.__service = oss2.Service(self.__auth, 'https://{}'.format(fittness.OSS[0]))
        self.__bucket = oss2.Bucket(self.__auth, 'https://{}'.format(fittness.OSS[0]), fittness.OSS[3])

    def get_sign_url(self, file_name, expires=60):
        return self.__bucket.sign_url('GET', file_name, expires)

    def object_exists(self, filename):
        return self.__bucket.object_exists(filename)

    def get_object(self, filename):
        remote_stream = self.__bucket.get_object(filename)
        return remote_stream

    def get_process_url(self, filename, process):
        file_name = filename
        now = func.get_ts()
        h = hmac.new(fittness.OSS[2],
                     'GET\n\n\n{}\n/{}/{}?{}'.format(now + 300, fittness.OSS[3], file_name, process),
                     sha)
        sig = urllib.quote(base64.encodestring(h.digest()).strip())
        url = 'https://{}.{}/{}?{}&OSSAccessKeyId={}&Expires={}&Signature={}'.format(
            fittness.OSS[3],
            fittness.OSS[0],
            file_name,
            process,
            fittness.OSS[1],
            now + 300,
            sig)
        return url

    def put_object(self, file_name, file_data):
        return self.__bucket.put_object(file_name, file_data)

    def put_object_from_file(self, remote_file, local_file):
        return self.__bucket.put_object_from_file(remote_file, local_file)

    def list_object(self, prefix):
        object_list = []
        for obj in oss2.ObjectIterator(self.__bucket, prefix=prefix):
            object_list.append(obj.key)
        return object_list

    def get_url_public(self, file_name):
        return 'https://{}.{}/{}'.format(fittness.OSS[3], fittness.OSS[0], file_name)


if __name__ == '__main__':
    oss = cli()
    print oss.list_object('1704300001/')
